<template>
  <div>
    <!-- file-list文件列表管理 -->
    <!-- on-preview控制浏览 -->
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="filelist"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
      :class="{disable:filelist.length===1}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="showProgress" :text-inside="true" :stroke-width="12" style="width:146px" :percentage="percent" status="success" />
    <el-dialog title="图片预览" :visible="showDialog" @close="showDialog=false">
      <img :src="imgUrl" style="width:100%" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDb5MQIyRghT1NYVDhxznMn26xazB9wiJg',
  SecretKey: 'B8sNeliRyLZaQG7xeBfCcqrjOrAJI4cx'
})
export default {
  data() {
    return {
      showProgress: false,
      percent: 0,
      filelist: [
        // {
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }

      ],
      imgUrl: '',
      showDialog: false
    }
  },
  methods: {
    //   上传时的钩子  点击浏览放大
    onPreview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 点击删除
    onRemove(file, fileList) {
      this.filelist = [...fileList]
    },
    // 文件状态被改变时
    onChange(file, fileList) {
      this.filelist = [...fileList]
    },
    // 覆盖默认上传行为
    httpRequest(params) {
      this.showProgress = true
      console.log(params)
      cos.putObject({
        Bucket: 'cc292-1306596884', /* 存储桶名称 */
        Region: 'ap-guangzhou', /* 地区 */
        Key: Date.now() + params.file.name, /* 文件名 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // console.log(this.filelist)
        if (!err) {
          this.filelist[0].url = 'http://' + data.Location
          //   手动告诉上传组件，这张图片已经上传成功
          this.filelist[0].status = 'success'
        }
        setTimeout(() => {
          this.showProgress = false
        }, 800)
      })
    },
    // 上传之前的钩子
    beforeUpload(file) {
      const whiteList = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      const size = 500 * 1024
      if (!whiteList.includes(file.type)) {
        this.$message.warning('上传图片只能是 JPG、GIF、BMP、PNG 格式 !')
        return false
      }
      if (size < file.size) {
        this.$message.warning('大小最大不能超过500k')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .disable{
    .el-upload--picture-card{
        display: none;
    }
}
</style>
